// import React from 'react';
import React, { Component, Fragment } from 'react';
import TodoItem from './TodoItem'
// class TodoList extends React.Component {
class TodoList extends Component {
  constructor(props) {
    super(props)
    this.state = {
      list: [],
      inputValue: ''
    }
    this.handleInputChange = this.handleInputChange.bind(this)
    this.handleBtnClick = this.handleBtnClick.bind(this)
    this.handleDelete = this.handleDelete.bind(this)
    this.pressEnter = this.pressEnter.bind(this)
  }
  
  pressEnter(e) {
    if(e.nativeEvent.keyCode === 13) {
      this.handleBtnClick()
    }
  }
  handleBtnClick() {
    if(this.state.inputValue) {
      this.setState({
        list: [...this.state.list, this.state.inputValue],
        inputValue: ''
      })
    }
    
    // this.state.list.push('hello world')
  }
  handleInputChange(e) {
    // console.log(e.target.value)
    this.setState({
      inputValue: e.target.value
    })
  }
  // handleItemClick(index) {
  //   // console.log(index)
  //   const list = [...this.state.list]
  //   list.splice(index, 1)
  //   this.setState({ list })
  // }
  handleDelete(index) {
    // console.log(index)
    const list = [...this.state.list]
    list.splice(index, 1)
    this.setState({ list })
  }

  getTodoItems() {
    return (
      this.state.list.map((item, index) => {
        return <TodoItem 
                 key={index} 
                 content={item} 
                 index={index}
                 delete={this.handleDelete}
               />
       // return <li key={index} onClick={this.handleItemClick.bind(this, index)}>{item}</li>
      })
    )
  }

  // 父组件通过属性的方式向子组件传递参数
  // 子组件通过props接收父组件传递过来的参数

  // React.Fragment可减少一层包裹元素
  render() {
    return (
      // <React.Fragment>
      <Fragment>
         <p style={{background: 'skyblue', color: 'white'}}
            className="todo-title"
         >hello sanday</p>
         <div>
           <input 
            value={this.state.inputValue} 
            onKeyPress={this.pressEnter} 
            onChange={this.handleInputChange} 
            type="text"
          />
           <button onClick={this.handleBtnClick}>add</button>
         </div>
        <ul>{ this.getTodoItems() }</ul>
      </Fragment>
      // </React.Fragment>
    )
  };
}

export default TodoList;
